/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief Implementation for Energy interface client library.
 * \author Antti Maula <antti.maula@tkk.fi>
 * \author Marek Matusiak
 *
 * $Id: EnergyClient.cpp,v 1.6 2009-10-23 13:56:43 morsko Exp $
 *
 */

#include "EnergyClient.hpp"
#include "EnergyData.hpp"

//*****************************************************************************
using namespace MaCI::Energy;
//*****************************************************************************
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CEnergyClient::CEnergyClient(gimi::GIMI *aGIMIPtr, 
                           const int aInterfaceMinor)
  : CSync(1,1), // Max One Mutex, Max one Condition
    CThread(1), // Max one Thread.
    CMaCI(aGIMIPtr, GIMI_PROTOCOL_MACI_ENERGY, aInterfaceMinor),
    iEnergyDataSequence(0),
    iEnergyCommandSequence(0),
    iLastEnergyData(),
    iEnergyClientCallback(NULL),
    iCallBackUserPtr(NULL)
{
  dPrint(4,"CEnergyClient %p constructed", this);
}
//*****************************************************************************

CEnergyClient::~CEnergyClient()
{
  DoClose();
  dPrint(4,"CEnergyClient %p destructed", this);
}
//*****************************************************************************

MaCI::EMaCIError CEnergyClient::DoOpen(void)
{

  EMaCIError result = KMaCIError;
  
  // Checks.
  if(!IsActive()) {

    // Do Subs. using the MaCI provided function.
    result = SubscribeToInterface();

    // If all inits were fine...
    if (result == KMaCIOK) {
      // Start the Thread
      SetActive(true);
      EnableSynchronousMessageReply();
      CThread::RunThread();
      dPrint(4,"CEnergyClient::DoOpen() was succesfull.");
    }

  } else {
    dPrint(4,"EnergyClient already Active, not Opening again.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CEnergyClient::DoClose(void)
{
  EMaCIError result = KMaCIError;
  
  if(IsActive()) {
    SetActive(false);

    // Wait for thread to complete.
    CThread::SetRequestTermination();
    /* CThread::CancelThread(); //Removed by script */
   
    result = UnsubscribeToInterface(TimeoutValue(2000));

    Notify(KEventEnergyData);

    CThread::WaitThread();
   
  
    if(result == KMaCIOK){
      dPrint(4,"Succesfully closed EnergyClient");    
    }else{
      dPrint(4,"Unsubscribing failed at EnergyClient!");
    }
   
    
  } else {
    dPrint(4, "EnergyClient not active, so not Closing.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************
bool CEnergyClient::SetEnergy(const float energyLevel)
{
  // Create Pos container, and set it to use Internal BinBag
  CEnergyData en;
  en.CreateInternalBinBag();

  // Assign new data (Call TTimestamp() with no parameters for current time)
  en.SetTimestamp(Common::TTimestamp());
  en.SetCommand(KCommandSetEnergy);
  en.SetEnergyLevel(energyLevel);

  // Send to GIMnet for default target.
  const EMaCIError e = SendInterfaceMessage(en.GetBinBagContainerPtr()->GetBuffer(),
                                            en.GetBinBagContainerPtr()->GetBufferSize());

  return (e == KMaCIOK);
}

//*****************************************************************************
bool CEnergyClient::SetMaxEnergy(const float energyLevel)
{
  // Create Pos container, and set it to use Internal BinBag
  CEnergyData en;
  en.CreateInternalBinBag();

  // Assign new data (Call TTimestamp() with no parameters for current time)
  en.SetTimestamp(Common::TTimestamp());
  en.SetCommand(KCommandSetMaxEnergy);
  en.SetMaxEnergyLevel(energyLevel);

  // Send to GIMnet for default target.
  const EMaCIError e = SendInterfaceMessage(en.GetBinBagContainerPtr()->GetBuffer(),
                                            en.GetBinBagContainerPtr()->GetBufferSize());

  return (e == KMaCIOK);
}

//*****************************************************************************
bool CEnergyClient::SetConsumption(const float consumption)
{
  // Create Pos container, and set it to use Internal BinBag
  CEnergyData en;
  en.CreateInternalBinBag();

  // Assign new data (Call TTimestamp() with no parameters for current time)
  en.SetTimestamp(Common::TTimestamp());
  en.SetCommand(KCommandSetConsumption);
  en.SetConsumption(consumption);

  // Send to GIMnet for default target.
  const EMaCIError e = SendInterfaceMessage(en.GetBinBagContainerPtr()->GetBuffer(),
                                            en.GetBinBagContainerPtr()->GetBufferSize());

  return (e == KMaCIOK);
}


//*****************************************************************************

bool CEnergyClient::GetEnergyEvent(CEnergyData &aData,
                                 unsigned int *aSeq,
                                 const unsigned int aTimeout_ms)
{  
  bool result = false;
  
  // Fallback in case the class is not active.
  if (!IsActive()) return false;

  Lock();
  
  if (aSeq == NULL) {
    // No sequence number defined. Just do direct copy of local data - no sync
    aData = iLastEnergyData;
    result = true;
    
  } else {
    
    if (iEnergyDataSequence <= *aSeq) {
      int time_left = aTimeout_ms;
      unsigned int time_begin = ownTime_get_ms();

      // The available scan is older than requested - must wait for time_left
      do {
        Wait(time_left, KEventEnergyData);
	time_left = aTimeout_ms - ownTime_get_ms_since(time_begin);
	
      } while(IsActive() && iEnergyDataSequence < *aSeq && time_left > 0);
      
      // Now, check whether the waiting resulted in the correct sequence
      if (iEnergyDataSequence > *aSeq) {
	// Yes :)
	aData = iLastEnergyData;
	*aSeq = iEnergyDataSequence;
	result = true;
        //dPrint(1,"Got data. *aSeq = %d, iEnergyDataSequence = %d", *aSeq, iEnergyDataSequence);
	
      } else {
	// No :(
	dPrint(3, "Failed to get EnergyData! (Timeout %dms)",
	       aTimeout_ms);
      }
      
    } else {
      // The available data is newer or matching.
      aData = iLastEnergyData;
      *aSeq = iEnergyDataSequence;
      //      dPrint(1,"Got data. *aSeq = %d, iEnergyDataSequence = %d", *aSeq, iEnergyDataSequence);
      result = true;
    }
  }
  
  Unlock();
  
  return result;
}
//*****************************************************************************

//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
/**
 * This function is an _EXAMPLE_ of a directly receiving
 * function. When this function model is used, the Client class
 * doesn't have to implement a separate thread. (ProcessMessage and
 * ThreadFunction are not used). However, this means that no special
 * processing can be done by the interface hence this model is only
 * suitable for simple interfaces. This can ofcourse be later changed
 * without changing the public interface, so it's not a
 * architecturally significant decision. Use of this model is also
 * encouraged if possible, as it saves one extra thread thus saving a
 * (minimal) fraction of system resources.
 *
 * As this EnergyClient uses the more complex processing model as
 * example, this code block is disabled with precompiler directive,
 * but left here as on fully working example of receiving MaCI
 * dataelements directly from GIMI.
 */
#if 0
bool CEnergyClient::GetEnergyEvent(CEnergyData &aData,
                                 const unsigned int aTimeout_ms);
{
  EMaCIError result;
  gimi::GIMIMessage gmsg;
  
  if (IsActive()) {
    
    // Call the ReceiveMessage wrapper with 2s timeout
    result = ReceiveInterfaceMessage(gmsg, aTimeout_ms);
    
    // If result is OK, process the msg.
    if (result == KMaCIOK) {
      bool r;
      gim::binbag::CBinBag bb;
      CEnergyData d;
      
      // Decode BinBag.
      r = bb.Decode(gmsg.getData(), gmsg.getDatalength());
      if (r) {
        // BinBag OK. Decode EnergyData.
        r = d.DecodeFrom(&bb);
        if (r && d.GetEnergyEvent()) {
          // EnergyData ok. Copy to caller.
          aData.Copy(d);
          
        } else {
          result = KMaCIInvalidFormat;
          
        }
        
      } else {
        result = KMaCIInvalidFormat;
        
      }
    }
  } else {
    result = KMaCINotActive;

  }
  
  return (result == KMaCIOK);
}
#endif
//*****************************************************************************

bool CEnergyClient::GetCommandReply(CEnergyData &aData, const int aMessageID, 
                                   const int aTimeout_ms)
{ 
  EMaCIError result;
  SMessageSource ms; // Compulsory for call to
                     // Receivesynchronousmessagereply, not used here
                     // though.

  // Call the ReceiveMessage wrapper with 2s timeout
  result = ReceiveSynchronousMessageReply(aData, ms, aMessageID, aTimeout_ms);
  
  // If result is OK, process the msg.
  if (result == KMaCIOK) {
    // Got message OK.  Basicly we don't need to do anything here, but
    // some interface may want to do some checks: for example, the
    // received message contains some specific element or information
    // before it is accepted.
  }
  
  return (result == KMaCIOK);
}
//*****************************************************************************

bool CEnergyClient::SendCommand(const CEnergyData &aEnergyData, const int aMessageID)
{
  EMaCIError result = KMaCIError;
  
  if (IsActive()) {
    if (aEnergyData.GetCommand()) {
      // Send.
      SendInterfaceMessage(aEnergyData.GetBinBagContainerPtr()->GetBuffer(),
                           aEnergyData.GetBinBagContainerPtr()->GetBufferSize(),
                           aMessageID);
      
      dPrint(10,"SendInterfaceMessage called: %d:%d (%d bytes of payload sent)",
             iInterfaceMajor, iInterfaceMinor, 
             aEnergyData.GetBinBagContainerPtr()->GetBufferSize());
      // Result
      result = KMaCIOK;
      
    } else {
      dPrint(2,"No 'TCommand' element in provided CEnergyData object. Will not send!");
      result = KMaCIInvalidFormat;

    }
   
  } else {
    dPrint(2,"Unable to send EnergyData - Interface is not active! (Open() not called?)");
    result = KMaCINotActive;

  }


  return (result == KMaCIOK);
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

int CEnergyClient::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CEnergyData id;
  bool r;

  r = bb.Decode(msg.getData(), msg.getDatalength());
  if (r) {
    // Succesfully decoded as BinBag.
    r = id.DecodeFrom(&bb);
    if (r) {
      // Succesfully decoded as Energy, now handle contents
      Lock();
      if (id.GetEnergyEvent()) {
        iLastEnergyData = id;
        ++iEnergyDataSequence;
        Notify(KEventEnergyData);
        dPrint(10,"Got EnergyData, Sequence now %u", iEnergyDataSequence);
      }
      Unlock();
      
      // Call the handler if set.
      if (iEnergyClientCallback) {
        dPrint(8,"Got Callback for EnergyDataEvent - executing!");
        iEnergyClientCallback->OnEnergyDataEvent(id,
                                               iEnergyDataSequence,
                                               *this);
        dPrint(8,"Callback for EnergyDataEvent - execution complete!");
      } 

    } else {
      dPrint(4,"WARNING: Received Energy interface message, but failed to decode as EnergyData!");
      
    }
  }
  
  return result;
}

//*****************************************************************************

int CEnergyClient::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(8, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(IsActive()) {
    // Call the ReceiveMessage wrapper with 1s timeout
    e = ReceiveInterfaceMessage(gmsg, 5000);
    if (e == KMaCIOK) {
      ProcessMessage(gmsg);

    } else if (e != KMaCITimeout) {
      /*      // Increment hard error count
      ++hard_error_count;
      
      // Check whether the hard error count limit is still under limit. 
      if (hard_error_count < hard_error_count_limit) {
        // Other error, try to recover by sleeping one second.
        dPrint(10,"ProcessMessage returned error %u, trying to recover by sleeping 1000ms (%u attempts left)",
               e, hard_error_count_limit-hard_error_count);
        ownSleep_ms(1000);

      } else {
        dPrint(3,"Error Recovery failed, EnergyClient ThreadFunction terminating...");

        // Break the while().
        break;
        }*/

      if(IsActive()){
        dPrint(10,"ProcessMessage returned error %u, trying to recover by sleeping 1000ms",
               e);
        ownSleep_ms(1000);
      }
      
    }
  }
  
  dPrint(8, "GIMIMessage handler stopped");
  SetActive(false);

  return result;
}
//*****************************************************************************
CEnergyClientCallback *CEnergyClient::GetEnergyClientCallBack(void) {
    return iEnergyClientCallback;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
